package fr.greta.centre.dao;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import javax.naming.NamingException;

import fr.greta.centre.metier.Candidat;
import fr.greta.centre.metier.Etat;

public class EtatDAOImpl implements EtatDAO{

	@Override
	public int save(Etat t) throws SQLException {
		// TODO Auto-generated method stub
		return 0;
	}
	
public int updateEtat(int idEtat, int idPromo, int idCandidat) throws SQLException {
		
				
		try {

			String sql = "UPDATE centre_formation.candidature SET etat_candidature=?, date_effet=? WHERE id_candidat=? AND id_promotion=?";
			
			Connection conn  = Bd.getConnect();
			
			PreparedStatement st = conn.prepareStatement(sql);
			java.sql.Date date = new java.sql.Date(new java.util.Date().getTime());
			
			st.setInt(1, idEtat);
			st.setDate(2, date);
			st.setInt(3, idCandidat);
			st.setInt(4, idPromo);	
			
			st.executeUpdate();
			conn.close();
			return 1;
		}

		catch (SQLException e) {
			System.out.println(e.getMessage());
			return 0;
		}
	}
	

	@Override
	public boolean delete(int id) throws SQLException {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public Etat findByKey(int id) throws SQLException {
		Statement st;
		st = Bd.getConnect().createStatement();
		String sql = "SELECT * FROM etat_candidature" +
				" WHERE etat_candidature = " + id;
		ResultSet rs = st.executeQuery(sql);
		rs.next();
		Etat etat = new Etat(id, rs.getString("libelle"));
		st.getConnection().close();
		return etat;
		
		
	}

	@Override
	public List<Etat> findAll() throws SQLException {
		
		ResultSet resultat;
		ArrayList<Etat> lesEtats = new ArrayList<Etat>();

		try {
			Connection connect = Bd.getConnect();
			String sql = "SELECT * FROM etat_candidature SORT BY id_promotion ";
			resultat = connect.createStatement().executeQuery(sql);
			while (resultat.next()) {

				Etat unEtat = new Etat();
						int id = resultat.getInt("etat_candidature");
						String libelle = resultat.getString("libelle");
						unEtat.setIdEtat(id);
						unEtat.setLibelle(libelle);
				lesEtats.add(unEtat);
			}
			connect.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return lesEtats;
	
	}

}
